const express=require("express");
const exphbs=require('express-handlebars');
const bodyParser=require('body-parser');
const mongoose=require('mongoose');
const methodOverride=require('method-override');
const session=require('express-session');
const flash=require('connect-flash');
const path =require('path');
const passport= require('passport');
const app = express();
//load routes
const ideas=require('./routes/ideas')
const users=require('./routes/users')

require('./config/passport')(passport);

const db=require('./config/database');
//connect MongoDb
mongoose.connect(db.mongoURL)
    .then(()=>{
        console.log("mongodb connected...");
    })
    .catch((err)=>{
        console.log(err);
    })
//使用静态文件
app.use(express.static(path.join(__dirname,"public")));
//method-override middleware
app.use(methodOverride('_method'));
//中间件
app.engine('handlebars',exphbs({
    defaultLayout: 'main',
    runtimeOptions: {
        allowProtoPropertiesByDefault: true,
        allowProtoMethodsByDefault: true,
    },
}));
app.set('view engine','handlebars');

// session flash middleware
app.use(session({
    secret:'secret',
    resave:true,
    saveUninitialized:true,
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//配置全局变量
app.use((req,res,next)=>{
    res.locals.success_msg =req.flash('success_msg');//res.locals.这个自定义
    res.locals.error_msg =req.flash('error_msg');
    res.locals.error =req.flash('error');
    res.locals.user =req.user||null;
    next();
})
//配置路由
app.get("/",(req,res)=>{
    const title="大家好，我是峰峰688！！！！";
    res.render("index",{
        title:title
    });
})
app.get("/about",(req,res)=>{
    res.render("ABOUT");
})
//使用routes
app.use("/ideas",ideas);
app.use("/users",users);



const port=process.env.PORT||5000;
app.listen(port,()=>{
    console.log(`http://127.0.0.1:${port}/`);
})